package com.imdroid.lite.net.udp;

import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.util.HashMap;

import com.imdroid.lite.IMDroid;
import com.imdroid.lite.model.TeamTalk;
import com.imdroid.lite.process.PlaySoundProcess;

public class FileReceiver {
	
	private FileReceiver(){}
	
	private static HashMap<Long, FileReceiver> receivers = new HashMap<Long, FileReceiver>();
	
	private String fileName;
	private RandomAccessFile rafile;
	private short totalParts;
	private short currentMaxPart; // 用来记住收到哪一个包
	private long msgId;
	private int from;
	private int fileLength;
	private String fromNickName;
	
	public static FileReceiver getInstance(long msgId, short part){
		FileReceiver fr = null;
		// 这里暂时这样做着，因为无法保证第一个包来到的编号是0，
		if(part == 0){
			fr = new FileReceiver();
			fr.msgId = msgId;
			receivers.put(msgId, fr);
		} else {
			fr = receivers.get(msgId);
//			为空的时候，表明已经有包顺序不对，抛弃，部分丢包问题不处理
//			if(fr == null){
//				fr = new FileReceiver();
//				receivers.put(msgId, fr);
//			}
		}
		return fr;
	}
	
	public static HashMap<Long, FileReceiver> getAllReceivers(){
		return receivers;
	}

	
	public void process(DatagramPacket packet, short part){
		System.out.println("Processing ... " + part);
		if(part == 0){
			String content[] = null;
			try {
				content = new String(packet.getData(), 22, packet.getLength() - 22, "UTF-8").split("&&");
				this.fileName = content[0];
				this.fromNickName = content[1];
				this.from = IntegerTransfer.byteToInt(packet.getData(), 9);
				if(content.length > 3)
					this.fileLength = Integer.parseInt(content[2]);
				else
					this.fileLength = 0;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			try {
				rafile = new RandomAccessFile(IMDroid.TEMP_FOLDER  + fileName, "rws");
				rafile.setLength(fileLength);
			} catch (Exception e) {
				e.printStackTrace();
			}
			currentMaxPart = 0;
			totalParts = IntegerTransfer.byteToShort(packet.getData(), 18);
			return;
		}
		
		try{
			rafile.seek((part - 1) * 512);
			rafile.write(packet.getData(), 22, packet.getLength() - 22);
		} catch(Exception e){
			e.printStackTrace();
		}
		if(part > currentMaxPart)
			currentMaxPart = part;
		if(part == totalParts){
			try{
				rafile.close();
				rafile = null;
			} catch(Exception e){
				e.printStackTrace();
			}
			receivers.remove(msgId);
			TeamTalk tt = new TeamTalk();
			tt.setFile(IMDroid.TEMP_FOLDER + fileName);
			tt.setFileNameInServer(fileName);
			tt.setMemberId(from);
			tt.setMemberName(fromNickName);
			PlaySoundProcess.speak2(tt);
		}
	}
}
